{% extends 'app_doc/user/user_base.html' %}
{% load static %}
{% load i18n %}
{% block title %}{% trans "文集设置" %}{% endblock %}
{% block custom_element %}
<link href="{% static 'tagsInput/tagsinput.css' %}" rel="stylesheet" type="text/css"/>
<link rel="stylesheet" href="{% static 'editor.md/css/editormd.css' %}?version={{mrdoc_version}}" />
<link href="{% static 'mrdoc/mrdoc-editor.css' %}?version={{mrdoc_version}}" rel="stylesheet">
{% endblock %}
{% block content %}
<div class="layui-card">
    <div class="layui-card-body">
    <div class="layui-row" style="padding-left:15px;">
        <span class="layui-breadcrumb" lay-separator=">">
          <a href="{% url 'manage_project' %}">{% trans "文集管理" %}</a>
          <a><cite>{% trans "文集设置" %}</cite></a>
          <a><cite>{% trans "文集：" %}{{pro.name}}</cite></a>
        </span>
    </div>
    </div>
</div>

<div class="layui-card">
    <div class="layui-card-body">
    <div class="layui-tab">
        <ul class="layui-tab-title">
            <li class="layui-this">{% trans "基础信息" %}</li>
            <li>{% trans "权限配置" %}</li>
            {% if enable_project_report %}
            <li>{% trans "下载配置" %}</li>
            {% endif %}
            <li>{% trans "管理控制" %}</li>
        </ul>
        <div class="layui-tab-content">
            <!-- 文集基础信息配置 -->
            <div class="layui-tab-item layui-show layui-form">
                <div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">{% trans "文集名称" %}</label>
                        <div class="layui-input-inline" style="width: 30px;">
                            <button class="layui-btn layui-btn-primary layui-btn-sm" id="project-icon-select">
                                {% if pro.icon %}
                                <svg class="icon" aria-hidden="true"><use xlink:href="{% if pro.icon %}#{{pro.icon}}{% else %}#mrdoc-icon-pro-2{% endif %}"></use></svg>
                                {% else %}
                                <i class="layui-icon layui-icon-addition"></i>
                                {% endif %}
                            </button>
                            <input type="hidden" name="picon" id="picon" value="{{pro.icon}}"/>
                            <div class="layui-anim layui-anim-upbit layui-iconpicker hide-project-icon-list" id="project-icon-select-box">
                                <div class="layui-iconpicker-list" id="mrdoc-project-icon-list"></div>
                            </div>
                        </div>
                        <div class="layui-input-inline" style="min-width: 300px;">
                            <input class="layui-input" type="text" id="pname" style="margin-bottom:10px;" placeholder="{% trans '输入文集名' %}" required  lay-verify="required" value="{{pro.name}}">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">文集水印</label>
                        <div class="layui-input-block">
                            <input type="checkbox" name="is_watermark" id="is_watermark" lay-skin="switch" lay-text="开启|关闭" {% if pro.is_watermark %}checked{% endif %}>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">水印文字</label>
                        <div class="layui-input-inline">
                            <input type="input" class="layui-input" name="watermark_value" id="watermark_value" value="{{pro.watermark_value}}">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">{% trans "文集简介" %}</label>
                        <div class="layui-input-block">
                            <div id="editor-md">
                                <textarea style="display: none;">{{pro.intro}}</textarea>
                            </div>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <div class="layui-input-block">
                            <button class="layui-btn layui-btn-primary layui-btn-sm" id="modify-project-btn"><i class="layui-icon layui-icon-edit"></i>{% trans "立即修改" %}</button>
                        </div>
                    </div>
                </div>
            </div>
            <!-- 文集权限配置 -->
            <div class="layui-tab-item">
                <div class="layui-form">
                    <div class="layui-form-item">
                        <label class="layui-form-label">{% trans "浏览权限" %}</label>
                        <div class="layui-input-block">
                            <input type="radio" name="role" value="0" title="{% trans '公开' %}" {% if pro.role == 0 %} checked {%endif%} lay-filter="role">
                            <input type="radio" name="role" value="1" title="{% trans '私密' %}" {% if pro.role == 1 %} checked {%endif%} lay-filter="role">
                            <input type="radio" name="role" value="2" title="{% trans '指定用户可见' %}" {% if pro.role == 2 %} checked {%endif%} lay-filter="role">
                            <input type="radio" name="role" value="3" title="{% trans '访问码可见' %}" {% if pro.role == 3 %} checked {%endif%} lay-filter="role">
                        </div>
                    </div>
        
                    <div class="layui-form-item" style="{% if pro.role == 3 %}{% else %}display:none;{% endif %}" id="role-pwd">
                        <label class="layui-form-label">{% trans "访问码" %}</label>
                        <div class="layui-input-inline">
                          <input type="text" name="viewcode" id="viewcode" placeholder="{% trans '请输入访问码' %}" autocomplete="off" class="layui-input" value="{% if pro.role_value != None %}{{pro.role_value}}{% endif %}">
                        </div>
                        <div class="layui-form-mid layui-word-aux">{% trans "不少于4位数" %}</div>
                    </div>
        
                    <div class="layui-form-item" style="{% if pro.role == 2 %}{% else %}display:none;{% endif %}" id="role-user">
                        <label class="layui-form-label">{% trans "允许用户" %}</label>
                        <div class="layui-input-block">
                            <div class="tagsinput-primary form-group">
                                <input name="tagsinput" id="tagsinputval" class="tagsinput" data-role="tagsinput" value="{% if pro.role_value != None %}{{pro.role_value}}{% endif %}" placeholder="{% trans '请输入用户名，回车输入多个用户' %}">
                            </div>
                        </div>
                    </div>
        
                    <div class="layui-form-item">
                        <div class="layui-input-block">
                          <button class="layui-btn layui-btn-primary layui-btn-sm" id="modify-project-role">{% trans "修改权限" %}</button>
                        </div>
                    </div>
                </div>
            </div>
            <!-- 下载和导出 -->
            {% if enable_project_report %}
            <div class="layui-tab-item">
                <div class="layui-form">
                    {% load project_filter %}
                    <div class="layui-form-item">
                        <blockquote class="layui-elem-quote">{% trans "注意：开启某类型文件下载后，请先点击“生成或更新XXX文件”，EPUB格式文件不支持思维导图、公式、流程图等图形" %}</blockquote>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">{% trans "EPUB下载" %}</label>
                        <div class="layui-input-block">
                            <input type="checkbox" name="download_epub"
                               {% if pro.id|report_status_epub == 1 %} checked {% endif %}
                               lay-skin="switch" lay-text="{% trans '允许|禁止' %}">
                               <!-- 判断后台是否开启导出，如果开启，则显示 -->
                                <a href="javascript:void(0);" onclick="reportFile('{{pro.id}}','epub')"><i class="layui-icon layui-icon-refresh"></i><u>{% trans "生成或更新EPUB文件" %}</u></a>
                                {% if project_files %}
                                    {% for file in project_files %}
                                        {% if file.file_type == 'epub' %}
                                            | <a href="{{file.file_path}}" target="_blank"><i class="layui-icon layui-icon-download-circle"></i><u>{% trans "下载文集EPUB文件" %}</u></a>
                                        {% else %}
                                            
                                        {% endif %}
                                    {% endfor %}
                                {% else %}
                                | <span style="color: #ff213b;">{% trans "未生成文集导出文件" %}</span>
                                {% endif %}
                        </div>
                    </div>
                    <hr>
                    <div class="layui-form-item">
                        <label class="layui-form-label">{% trans "PDF下载" %}</label>
                        <div class="layui-input-block">
                            <input type="checkbox" name="download_pdf"
                               {% if pro.id|report_status_pdf == 1 %} checked {%endif%}
                               lay-skin="switch" lay-text="{% trans '允许|禁止' %}">
                               <!-- 判断后台是否开启导出，如果开启，则显示 -->
                                <a href="javascript:void(0);" onclick="reportFile('{{pro.id}}','pdf')" style=""><i class="layui-icon layui-icon-refresh"></i><u>{% trans "生成或更新PDF文件" %}</u></a>
                                {% if project_files %}
                                    {% for file in project_files %}
                                        {% if file.file_type == 'pdf' %}
                                            | <a href="{{file.file_path}}" target="_blank"><i class="layui-icon layui-icon-download-circle"></i><u>{% trans "下载文集PDF文件" %}</u></a>
                                        {% else %}
                                            
                                        {% endif %}
                                    {% endfor %}
                                {% else %}
                                | <span style="color: #ff213b;">{% trans "未生成文集导出文件" %}</span>
                                {% endif %}
                        </div>
                    </div>
                    <hr>
                    <div class="layui-form-item">
                        <div class="layui-input-block">
                          <button class="layui-btn layui-btn-primary layui-btn-sm" id="modify-project-download">{% trans "保存文集导出配置" %}</button>
                        </div>
                    </div>
                    
                </div>
            </div>
            {% endif %}
            <!-- 文集删除和转让 -->
            <div class="layui-tab-item">
                <div class="layui-row">
                    <div style="float: left;">
                        <strong>{% trans "导出文集" %}</strong>
                        <p>{% trans "将文集内的文档以Markdown（.md）的形式导出为zip压缩文件" %}</p>
                    </div>
                    <button class="layui-btn layui-btn-primary" style="float: right;" id="export-project">{% trans "导出文集" %}</button>
                </div>
                <hr>
                <div class="layui-row">
                    <div style="float: left;">
                        <strong>{% trans "转让文集" %}</strong>
                        <p>{% trans "将文集的管理权限和文集下自己创建的文档转让给站点的其他用户" %}</p>
                    </div>
                    <a class="layui-btn layui-btn-primary" style="float: right;" id="transfer-project" href="{% url 'manage_pro_transfer' pro.id %}">{% trans "转让文集" %}</a>
                </div>
                <hr>
                <div class="layui-row">
                    <div style="float: left;">
                        <strong>{% trans "删除文集" %}</strong>
                        <p>{% trans "删除文集及文集下的所有文档" %}</p>
                    </div>
                    <button class="layui-btn layui-btn-warm" style="float: right;" id="delete-project">{% trans "删除文集" %}</button>
                </div>
            </div>
            
        </div>
    </div>
    </div>
</div>
{% endblock %}
{% block custom_script %}
<script src="{% static 'iconFont/iconfont.js' %}"></script>
<script src="{% static 'jquery/3.1.1/jquery.min.js' %}"></script>
<script src="{% static 'layui/layui.js' %}"></script>
<script src="{% static '/tagsInput/tagsinput.js' %}" type="text/javascript" charset="utf-8"></script>
<script>
    $.ajaxSetup({
        data: {csrfmiddlewaretoken: '{{ csrf_token }}' },
    });
    var tree = layui.tree;
    var layer = layui.layer;
    var form = layui.form;
    var element = layui.element;

    var layer = layui.layer;
    //监听单选事件
    form.on('radio(role)', function(data){
        console.log(data.elem); //得到radio原始DOM对象
        console.log(data.value); //被点击的radio的value值
        if(data.value in [0,1]){
                $("#role-pwd").css("display","none");
                $("#role-user").css("display","none");
        }else if(data.value == 2){
                $("#role-user").css("display","block");
                $("#role-pwd").css("display","none");
        }else if(data.value == 3){
                $("#role-user").css("display","none");
                $("#role-pwd").css("display","block");
        }
    });
    // 动态生成文集图标列表
    for(var i=1;i<44;i++){
            var icon_elem = '<div class="layui-iconpicker-icon-item" style="width:20%" data-icon="mrdoc-icon-pro-'+ i +'"><svg class="icon" aria-hidden="true"><use xlink:href="#mrdoc-icon-pro-'+ i +'"></use></svg></div>'
            $("#mrdoc-project-icon-list").append(icon_elem)
        }
        // 点击图标选择按钮
        $("#project-icon-select").click(function(){
            $("#project-icon-select-box").toggleClass("hide-project-icon-list")
        });
        // 选中图标
        $(".layui-iconpicker-icon-item").click(function(e){
            var selected_icon = e.currentTarget.dataset.icon;
            var selected_icon_svg = '<svg class="icon" aria-hidden="true"><use xlink:href="#'+ selected_icon +'"></use></svg>' 
            console.log(selected_icon)
            $("#project-icon-select").html(selected_icon_svg);
            $("#picon").val(selected_icon);
            $("#project-icon-select-box").toggleClass("hide-project-icon-list");
        });
    //修改文集基础信息
    modifyProject = function(pro_id,pro_name,pro_intro){
        layer.load(1);
        var project_data = {
            'picon':$("#picon").val(),
            'pro_id':'{{pro.id}}',
            'name':$("#pname").val(),
            'desc':editor.getMarkdown(),
            'is_watermark':$("input[name=is_watermark]")[0].checked,
            'watermark_value':$("#watermark_value").val(),
        }
        $.post("{% url 'modify_project' %}",project_data,function(r){
            layer.closeAll('loading'); //关闭loading
            if(r.status){
                //修改成功
                //window.location.reload();
                layer.msg("修改成功")
            }else{
                //修改失败，提示
                // console.log(r)
                layer.msg(r.data)
            }
        })
    };
    $("#modify-project-btn").click(function(){
        modifyProject();
    });
    // 修改文集权限
    modifyProjectRole = function(){
        layer.load(1);
        var role_data = {
            'role':$("input[name='role']:checked").val(),
            'tagsinput':$("#tagsinputval").val(),
            'viewcode':$("#viewcode").val(),
        }
        $.post("{% url 'modify_pro_role' pro.id %}",role_data,function(r){
            layer.closeAll('loading'); //关闭loading
            if(r.status){
                //修改成功
                //window.location.reload();
                layer.msg("修改成功")
            }else{
                //修改失败，提示
                // console.log(r)
                layer.msg(r.data)
            }
        })
    };
    $('#modify-project-role').click(function(){
        modifyProjectRole();
    });
    // 修改文集导出配置
    modifyProjectDownload = function(){
        layer.load(1);
        var download_data = {
            'download_epub':$("input[name='download_epub']:checked").val(),
            'download_pdf':$("input[name='download_pdf']:checked").val(),
        }
        $.post("{% url 'modify_pro_download' pro.id %}",download_data,function(r){
            layer.closeAll('loading'); //关闭loading
            if(r.status){
                //修改成功
                layer.msg("修改成功")
            }else{
                //修改失败，提示
                // console.log(r)
                layer.msg(r.data)
            }
        })
    };
    $('#modify-project-download').click(function(){
        modifyProjectDownload();
    });
    // 生成文集文件
    reportFile = function(pro_id,types){
        layer.load(1)
        var data = {'pro_id':pro_id,'types':types};
        $.ajax({
            url:"{% url 'genera_project_file' %}",
            type:"post",
            data:data,
            success:function(r){
                layer.closeAll('loading');
                if(r.status){
                    layer.msg("生成完成")
                    window.location.reload();
                }else{
                    layer.msg("生成出错，请稍后重试")
                }
            },
            error:function(){
                layer.closeAll('loading');
                layer.msg("服务器异常")
            }
        })
    };
    // 删除文集
    delProject = function(pro_id){
        layer.open({
            type:1,
            title:'删除文集',
            area:'300px;',
            id:'delPro',//配置ID
            content:'<div style="margin-left:10px;">警告：此操作将删除文集及文集下所有文档！</div>',
            btn:['确定','取消'], //添加按钮
            btnAlign:'c', //按钮居中
            yes:function (index,layero) {
                layer.load(1);
                data = {
                    'pro_id':pro_id,
                }
                $.post("{% url 'del_project' %}",data,function(r){
                    layer.closeAll('loading'); //关闭loading
                    if(r.status){
                        //删除成功
                        layer.msg('删除成功，即将返回文集列表……',function(){
                            window.location.href = "{% url 'manage_project' %}"
                        })
                        //layer.close(index)
                    }else{
                        //删除失败，提示
                        console.log(r)
                        layer.msg(r.data)
                    }
                })
            },
        });
    };
    $('#delete-project').click(function(){
        delProject('{{pro.id}}')
    })
    //导出MD
    reportMd = function(pro_id){
        layer.open({
            type:1,
            title:"导出文集",
            area:"300px",
            id:"reportMd",
            content:'<div style="margin-left:10px;">将此文集下所有文档导出为MD文件并打包？</div>',
            btn:['确定','取消'], //添加按钮
            btnAlign:'c', //按钮居中
            yes:function (index,layero) {
                var load = layer.load()
                data = {
                    'project_id':pro_id,
                }
                $.post("{% url 'report_md' %}",data,function(r){
                    layer.closeAll('loading'); //关闭loading
                    if(r.status){
                        //导出成功
                        //文件下载提示
                        downloadMd(r.data)
                    }else{
                        //导出失败，提示
                        // console.log(r)
                        layer.msg(r.data)
                    }
                    layer.close(load)
                })
            },
        })
    };
    $("#export-project").click(function(){
        reportMd('{{pro.id}}');
    });
    //下载文件弹出框
    downloadMd = function(download_link){
        layer.open({
            type:1,
            title:"下载导出文档",
            area:"300px",
            id:"downloadMd",
            content:'<p style="text-align:center;color:red;">请尽快下载，避免失效！</p><br><a class="layui-btn layui-btn-fluid download-md-link" href="'+ download_link + '" download="mrdoc_report_md.zip" >点击下载文件(zip)</a>',
            //btn:['确定','取消'], //添加按钮
            //btnAlign:'c', //按钮居中
            success: function (layero, index) {
                $(layero).find('.download-md-link').click(function () {
                    layer.closeAll();
                })
        }
        })
    };

</script>
<!-- 文集简介的Editor.MD编辑器 -->
<script src="{% static 'editor.md/editormd.js' %}?version={{mrdoc_version}}"></script>
<script>
    // 视频iframe域名白名单
    var iframe_whitelist = '{{ iframe_whitelist }}'.split(',')
    var md_changed = false; //初始化一个变量，用于判断编辑器是否修改
    //初始化editormd
    var editormd_watch = true;
    var editormd_height = '500px'
    var editormd_toobar = [
            "undo", "redo", "|",
            "h2","h3","h4", "bold", "del", "italic", "quote","kaiSpan","mark",  
            "list-ul", "list-ol", "hr", "link", "reference-link", 
            "mindmap","echart","code", "code-block", 
            "emoji", "pagebreak", 
            "watch", "preview", 
        ]
    var editor = editormd("editor-md", {
        width       :   "100%",
        height      :   editormd_height,
        placeholder :   "道友，开始吧……",
        toolbarIcons : function() {
            return editormd_toobar
        },
        //自定义工具栏添加楷体按钮
        toolbarIconTexts : {
            kaiSpan : "楷",
        },
        //自定义工具栏添加图片按钮
        toolbarIconsClass : {
            imgUpload:'fa-image',
            attachment:'fa-upload',
            htmltable:'fa-table',
            mindmap:'fa-sitemap',
            echart:'fa-bar-chart',
            multimedia:'fa-youtube-play',
        },
        //设置自定义工具栏按钮的事件
        toolbarHandlers : {
            /**
             * @param {Object}      cm         CodeMirror对象
             * @param {Object}      icon       图标按钮jQuery元素对象
             * @param {Object}      cursor     CodeMirror的光标对象，可获取光标所在行和位置
             * @param {String}      selection  编辑器选中的文本
             */
             // 点击“楷”字图标的响应函数
            kaiSpan : function(cm, icon, cursor, selection) {
                //var cursor    = cm.getCursor();     //获取当前光标对象，同cursor参数
                //var selection = cm.getSelection();  //获取当前选中的文本，同selection参数
                // 替换选中文本，如果没有选中文本，则直接插入
                cm.replaceSelection('<span style="font-family:楷体">' + selection + "</span>");
                // 如果当前没有选中的文本，将光标移到要输入的位置
                if(selection === "") {
                    cm.setCursor(cursor.line, cursor.ch + 29);
                }
                // this == 当前editormd实例
                //console.log("testIcon =>", this, cm, icon, cursor, selection);
            },
            // 添加思维导图
            mindmap:function(cm,icon,cursor,selection){
                cm.replaceSelection('```mindmap\n' + selection + "\n```");
                if(selection === "") {
                    cm.setCursor(cursor.line+1, cursor.ch);
                }
            },
            // 添加echart图
            echart:function(cm,icon,cursor,selection){
                cm.replaceSelection('```echart\n' + selection + "\n```");
                if(selection === "") {
                    cm.setCursor(cursor.line+1, cursor.ch);
                }
            },
        },
        //设置语言
        lang : {
            toolbar : {
                kaiSpan : "添加楷体span标签",
                imgUpload:"添加图片到文档",
                attachment:"添加附件",
                htmltable:"添加表格",
                mindmap:"添加思维导图",
                echart:"添加Echarts图表",
                multimedia:"添加音频、视频",
            }
        },
        //配置项
        watch       :editormd_watch,
        pageBreak : true, //分页符
        path        :   "/static/editor.md/lib/",
        saveHTMLToTextarea : true,
        atLink      :   false,//禁用@链接
        tex         :   true,//开启科学公式
        toc         :   false,// 关闭列表目录
        tocm        :   false,//关闭下拉目录
        taskList    :   true,//开启任务列表
        tocDropdown :   false,
        emoji       :   true,//开启Emoji
        flowChart   :   true, //开启流程图
        sequenceDiagram : true, //开启序列图
        imageUpload    : true, //开启图片上传
        codeFold       :true, //代码折叠
        autoFocus       : false,
        htmlDecode     : "link,style,base,script,iframe", //过滤部分HTML标签
        imageFormats   : ["jpg", "jpeg", "gif", "png", "bmp", "webp"],
        imageUploadURL : "{% url 'upload_doc_img' %}",
        onchange:function(){
            md_changed = true;
            var wcnt = this.getMarkdown().length;
            $("#wordcount").text(wcnt);        },
        onload : function() {
            // this.insertValue(" ")
            var wcnt = this.getMarkdown().length;
            $("#wordcount").text(wcnt);
        }
    });

    //粘贴上传图片
    $("#editor-md").on('paste', function (ev) {
        var data = ev.clipboardData;
        var items = (event.clipboardData || event.originalEvent.clipboardData).items;
        for (var index in items) {
            var item = items[index];
            if (item.kind === 'file') {
                var blob = item.getAsFile();
                console.log(blob)
                var reader = new FileReader();
                reader.onload = function (event) {
                    var base64 = event.target.result;
                    //ajax上传图片
                    layer.load(1);
                    $.ajax({
                        url:"{% url 'upload_doc_img' %}",
                        type:"post",
                        data:{base:base64},
                        success:function(ret){
                            if (ret.success === 1) {
                                //新一行的图片显示
                                layer.closeAll("loading");
                                editor.insertValue("\n![](" + ret.url + ")");
                                editor.focus()
                            }else{
                                layer.closeAll("loading");
                                layer.msg("粘贴图片失败！")
                            }
                        },
                        error:function(){
                            layer.closeAll('loading');
                        }
                    })
                }; // data url!
                var url = reader.readAsDataURL(blob);
            }
        }
    });
    
    //未保存离开提示
    window.onbeforeunload =function() {
    　　 if(md_changed){
            //console.log("页面未保存数据")
            return 1;
        }else{
            return null;
        }
    };
</script>
{% endblock %}